#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#pragma comment(lib, "glaux.lib")

#include "windows.h"       // Header File For Windows
#include "gl/gl.h"         // Header File For The OpenGL32 Library
#include "gl/glu.h"        // Header File For The GLu32 Library
#include "gl/glaux.h"      // Header File For The Glaux Library
#include <SDL/SDL.h>

#define FALSE 0
#define TRUE 1

/*
 PLEASE NOTE: the program will require SDL.dll which is located in
              dev-c++'s dll directory. You have to copy it to you
			  program's home directory or the path.
 */
HDC	   hDC=NULL;   // Private GDI Device Context
HGLRC	   hRC=NULL;   // Permanent Rendering Context
HWND	   hWnd=NULL;  // Holds Our Window Handle
HINSTANCE   hInstance;  // Holds The Instance Of The Application

bool	keys[256];          // Array Used For The Keyboard Routine
bool	active=TRUE;        // Window Active Flag Set To TRUE By Default
bool	fullscreen=TRUE;    // Set To Fullscreen Mode By Default

LRESULT	CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);	// Declaration For WndProc

GLvoid ReSizeGLScene(GLsizei width, GLsizei height)
{
    if (height==0)			// Prevent A Divide By Zero By
    {
	height=1;			// Making Height Equal One
    }

    glViewport(0,0,width,height);	// Reset The Current Viewport

    glMatrixMode(GL_PROJECTION);	// Select The Projection Matrix
    glLoadIdentity();		// Reset The Projection Matrix

    // Calculate The Aspect Ratio Of The Window
    gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);

    glMatrixMode(GL_MODELVIEW);	// Select The Modelview Matrix
    glLoadIdentity();		// Reset The Modelview Matrix
}

int InitGL(GLvoid)				// All Setup For OpenGL Goes Here
{
    glShadeModel(GL_SMOOTH);		// Enable Smooth Shading
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);	// Black Background
    glClearDepth(1.0f);			// Depth Buffer Setup
    glEnable(GL_DEPTH_TEST);		// Enables Depth Testing
    glDepthFunc(GL_LEQUAL);			// The Type Of Depth Testing To Do

    // Really Nice Perspective Calculations
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    return TRUE;			 	// Initialization Went OK
}

int DrawGLScene(GLvoid)		// Here's Where We Do All The Drawing
{
    // Clear Screen And Depth Buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Reset The Current Modelview Matrix
    glLoadIdentity();
	
    // Place your code here!

    return TRUE;			// Keep Going
}

GLvoid KillGLWindow(GLvoid)			// Properly Kill The Window
{
    if (fullscreen)			// Are We In Fullscreen Mode?
    {
	ChangeDisplaySettings(NULL,0);	// witch Back To Desktop
	ShowCursor(TRUE);			// Show Mouse Pointer
	
    if (hRC)				// Do We Have A Rendering Context?
    {
	if (!wglMakeCurrent(NULL,NULL))	// Able To Release DC And RC?
	{
		MessageBox(NULL,"Release Of DC And RC Failed.",
		"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
	}

	if (!wglDeleteContext(hRC))		// Able To Delete The RC?
	{
		MessageBox(NULL,"Release Rendering Context Failed.",
		"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
	}
	hRC=NULL;				// Set RC To NULL
    }

    if (hDC && !ReleaseDC(hWnd,hDC))		// Are We Able To Release The DC
    {
	MessageBox(NULL,"Release Device Context Failed.",
	"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
	hDC=NULL;				// Set DC To NULL
    }

    if (hWnd && !DestroyWindow(hWnd))	// Able To Destroy The Window?
    {
	MessageBox(NULL,"Could Not Release hWnd.",
	"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
	hWnd=NULL;			// Set hWnd To NULL
    }

    if (!UnregisterClass("OpenGL",hInstance))// Able To Unregister Class?
    {
	MessageBox(NULL,"Could Not Unregister Class.",
	"SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
	hInstance=NULL;			// Set hInstance To NULL
    }
}

bool CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag){
    // First some standard Win32 window creating
    GLuint	PixelFormat;
    WNDCLASS	wc;
    DWORD		dwExStyle;	
    DWORD		dwStyle;	
    RECT		WindowRect;
    WindowRect.left=(long)0;
    WindowRect.right=(long)width;
    WindowRect.top=(long)0;		
    WindowRect.bottom=(long)height;	

    // fullscreen variable
    fullscreen=fullscreenflag;

    hInstance		= GetModuleHandle(NULL);
    wc.style		= CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc		= (WNDPROC) WndProc;
    wc.cbClsExtra		= 0;
    wc.cbWndExtra		= 0;
    wc.hInstance		= hInstance;
    wc.hIcon		= LoadIcon(NULL, IDI_WINLOGO);	
    wc.hCursor		= LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground	= NULL;			
    wc.lpszMenuName	= NULL;		
    wc.lpszClassName	= "OpenGL";	

    // Register the window class
    if (!RegisterClass(&wc))		
    {
	MessageBox(NULL,"Failed To Register The Window Class.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;			
    }

    // If fullscreen flag is set
    if (fullscreen)	
    {
	DEVMODE dmScreenSettings;
	memset(&dmScreenSettings,0,sizeof(dmScreenSettings));
	dmScreenSettings.dmSize=sizeof(dmScreenSettings);
	dmScreenSettings.dmPelsWidth	= width;
	dmScreenSettings.dmPelsHeight	= height;
	dmScreenSettings.dmBitsPerPel	= bits;	
	dmScreenSettings.dmFields=DM_BITSPERPEL|
                             	DM_PELSWIDTH | DM_PELSHEIGHT;

	// Try To Set Selected Mode And Get Results.
	if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
	{
		if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "OPENGL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
		{
			fullscreen=FALSE;
		}
		else
		{
			MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP);
			return FALSE;
		}
	}
    }

    if (fullscreen)	
    {
	dwExStyle=WS_EX_APPWINDOW;
	dwStyle=WS_POPUP;	
	ShowCursor(FALSE);	
    }
    else
    {
	dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;	
	dwStyle=WS_OVERLAPPEDWINDOW;	
    }

    AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);

    // Create The Window
    if (!(hWnd=CreateWindowEx(	dwExStyle,	
				"OpenGL",	
				title,		
				dwStyle |		
				WS_CLIPSIBLINGS |	
				WS_CLIPCHILDREN,
				0, 0,				
				WindowRect.right-WindowRect.left,
				WindowRect.bottom-WindowRect.top,
				NULL,			
				NULL,		
				hInstance,		
				NULL)))	
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Window Creation Error.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;			
    }

    // Tell the window how we want things to be..
    static	PIXELFORMATDESCRIPTOR pfd=
    {
	sizeof(PIXELFORMATDESCRIPTOR),
	1,			// Version Number
	PFD_DRAW_TO_WINDOW |	// Format Must Support Window
	PFD_SUPPORT_OPENGL |	// Format Must Support OpenGL
	PFD_DOUBLEBUFFER,		// Double Buffering
	PFD_TYPE_RGBA,		// Request An RGBA Format
	bits,			// Select Our Color Depth
	0, 0, 0, 0, 0, 0,		// Color Bits Ignored
	0,			// No Alpha Buffer
	0,			// Shift Bit Ignored
	0,			// No Accumulation Buffer
	0, 0, 0, 0,		// Accumulation Bits Ignored
	16,			// 16Bit Z-Buffer (Depth Buffer)  
	0,			// No Stencil Buffer
	0,			// No Auxiliary Buffer
	PFD_MAIN_PLANE,		// Main Drawing Layer
	0,			// Reserved
	0, 0, 0			// Layer Masks Ignored	
    };

    // Did We Get A Device Context?
    if (!(hDC=GetDC(hWnd)))	
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Can't Create A GL Device Context.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }

    // Did Windows Find A Matching Pixel Format?
    if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))	
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Can't Find A Suitable PixelFormat.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }
    // Are We Able To Set The Pixel Format?
    if(!SetPixelFormat(hDC,PixelFormat,&pfd))		
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Can't Set The PixelFormat.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }

    // Are We Able To Get A Rendering Context?
    if (!(hRC=wglCreateContext(hDC)))
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Can't Create A GL Rendering Context.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }

    // Try To Activate The Rendering Context
    if(!wglMakeCurrent(hDC,hRC))	
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Can't Activate The GL Rendering Context.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }

    ShowWindow(hWnd,SW_SHOW);	// Show The Window
    SetForegroundWindow(hWnd);	// Slightly Higher Priority
    SetFocus(hWnd);		// Sets Focus To The Window
    ReSizeGLScene(width, height);	// Set Up Our Perspective GL Screen

    // Initialize Our Newly Created GL Window
    if (!InitGL())
    {
	KillGLWindow();		// Reset The Display
	MessageBox(NULL,"Initialization Failed.",
	"ERROR",MB_OK|MB_ICONEXCLAMATION);
	return FALSE;		// Return FALSE
    }

    return TRUE;			// Success
}

LRESULT CALLBACK WndProc(	HWND hWnd,	// Handle For This Window
			UINT	uMsg,	// Message For This Window
			WPARAM	wParam,  // Additional Message Information
			LPARAM	lParam)	// Additional Message Information
{
	switch (uMsg)			// Check For Windows Messages
	{
		case WM_ACTIVATE:	// Watch For Window Activate Message
		{
			if (!HIWORD(wParam))// Check Minimization State
	
				active=TRUE;// Program Is Active
			}
			else
			{
				active=FALSE;// Program Is No Longer Active
			}

			return 0;	// Return To The Message Loop
		}

		case WM_SYSCOMMAND:	// Intercept System Commands
		{
			switch (wParam)	// Check System Calls
			{
				// Screensaver Trying To Start?
				case SC_SCREENSAVE:	
				// Monitor Trying To Enter Powersave?
				case SC_MONITORPOWER:
				return 0;	// Prevent From Happening
			}
			break;			// Exit
		}

		case WM_CLOSE:	// Did We Receive A Close Message?
		{
			PostQuitMessage(0);// Send A Quit Message
			return 0;		// Jump Back
		}

		case WM_KEYDOWN:		// Is A Key Being Held Down?
		{
			keys[wParam] = TRUE;// If So, Mark It As TRUE
			return 0;		// Jump Back
		}

		case WM_KEYUP:		// Has A Key Been Released?
		{
			keys[wParam] = FALSE;// If So, Mark It As FALSE
			return 0;			// Jump Back
		}

		case WM_SIZE:		// Resize The OpenGL Window
		{
 			// LoWord=Width, HiWord=Height
			ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); 
			return 0;			// Jump Back
		}
	}

	// Pass All Unhandled Messages To DefWindowProc
	return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

int WINAPI WinMain( HINSTANCE hInstance,	// Instance
		  HINSTANCE hPrevInstance,	// Previous Instance
		  LPSTR lpCmdLine,		// Command Line Parameters
		  int nCmdShow)		// Window Show State
{
	MSG	msg;			// Windows Message Structure
	BOOL	done=FALSE;		// Bool Variable To Exit Loop

	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?",
	"Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;	// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("APRON TUTORIALS",640,480,16,fullscreen))
	{
		return 0;		// Quit If Window Was Not Created
	}

	while(!done)		// Loop That Runs While done=FALSE
	{
		// Is There A Message Waiting?
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			// Have We Received A Quit Message?
			if (msg.message==WM_QUIT)
			{
				done=TRUE;// If So done=TRUE
			}
			else	// If Not, Deal With Window Messages
			{
				// Translate The Message
				TranslateMessage(&msg);
				// Dispatch The Message
				DispatchMessage(&msg);
			}
		}
		else			// If There Are No Messages
		{
			// Draw The Scene.
			// Active?  Was There A Quit Received?
			if ((active && !DrawGLScene()) || keys[VK_ESCAPE])
			{
				// ESC or DrawGLScene Signalled A Quit
				done=TRUE;
			}
			else		// Not Time To Quit, Update Screen
			{
				// Swap Buffers (Double Buffering)
				SwapBuffers(hDC);
			}

			if (keys[VK_F1])	// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;// If So Make Key FALSE
				KillGLWindow();	// Kill Our Current Window
				// Toggle Fullscreen / Windowed Mode
				fullscreen=!fullscreen;
				// Recreate Our OpenGL Window
				if (!CreateGLWindow("APRON TUTORIALS",
				640,480,16,fullscreen))
				{
					// Quit If Window Was Not Created
					return 0;
				}
			}
		}
	}

	// Shutdown
	KillGLWindow();		// Kill The Window
	return (msg.wParam);	// Exit The Program
}

/*int main(int argc, char *argv[]){
  SDL_Event event;
  float theta = 0.0f;

  SDL_Init(SDL_INIT_VIDEO);
  SDL_SetVideoMode(640, 480, 0, SDL_OPENGL | SDL_HWSURFACE | SDL_NOFRAME);

  glViewport(0, 0, 640, 480);
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClearDepth(1.0);
  glDepthFunc(GL_LESS);
  glEnable(GL_DEPTH_TEST);
  glShadeModel(GL_SMOOTH);
  glMatrixMode(GL_PROJECTION);
  glMatrixMode(GL_MODELVIEW);

  int done;
  for(done = 0; !done;){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glTranslatef(0.0f,0.0f,0.0f);
    glRotatef(theta, 0.0f, 0.0f, 1.0f);

    glBegin(GL_TRIANGLES);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex2f(0.0f, 1.0f);
    glColor3f(0.0f, 1.0f, 0.0f);
    glVertex2f(0.87f, -0.5f);
    glColor3f(0.0f, 0.0f, 1.0f);
    glVertex2f(-0.87f, -0.5f);
    glEnd();

    theta += .5f;
    SDL_GL_SwapBuffers();
    SDL_PollEvent(&event);
    if(event.key.keysym.sym == SDLK_ESCAPE)
      done = 1;
  }
  SDL_Quit();
  return(0);
}
*/
